package com.fingard.dsp.bank.directbank.hsbank01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.text.MFSHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.SmbFileUtil;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;

import static com.fingard.io.FileHelper.*;
import static com.fingard.text.StringHelper.trimEndFileSp;

/**
 * @author: liuxb
 * @create: 2019-12-24 15:00
 * @version: 1.0
 **/
public class HSBANK01BatPayRec extends HSBANK01Base implements IBatPayRec {
    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_req1988.reqHeader);
        retAts.reqSeqID = p_req1988.reqBatchNO;
        StringBuilder content = new StringBuilder();
        content.append("ACNO|CUR_CODE|ACNAME|CARDFLAG|AMT|POSTSCRIPT|\n");
        while (p_req1988.readRecord()) {
            //            收款账号|币种|收款账户名称|卡折标志|金额|附言|
            content.append(String.format("%s|%s|%s|%s|%s|%s|\n", p_req1988.readedDetail.recAct, convertCurToBank(p_req1988.readedDetail.payCur), p_req1988.readedDetail.recName, "", p_req1988.readedDetail.payAmount, p_req1988.readedDetail.askNumber));
        }
        String fileName = p_req1988.reqBatchNO + ".txt";
        String path = trimEndFileSp(bankFront.bkTransFolder);//去掉最后一个目录分隔符(若存在)
        boolean result = bankWriteFile(path, fileName, content);
        if (!result) {
            retAts.writeStart();
            retAts.writeRespCode("-1");
            retAts.writeRespInfo("写入文件" + path + "失败，请检查");
            retAts.writeEnd();
            return retAts;
        }

        HSBANK01Header bankHeader = new HSBANK01Header();
        bankHeader.trCode = "300002";
        bankHeader.reqNo = p_req1988.reqBatchNO;
//        bankHeader.reqNo = p_req1988.reqHeader.reqSeqID;
        bankHeader.fileFlag = "1";
        XmlTextWriter xmlWriter = new XmlTextWriter();
        writeCommonHeader(xmlWriter, bankHeader);
        xmlWriter.writeStartElement("body");
        xmlWriter.writeElementString("batch_no", p_req1988.reqBatchNO);//批次号
        xmlWriter.writeElementString("pay_acno", p_req1988.ownAct);//付款账号
        xmlWriter.writeElementString("pay_cur_code", convertCurToBank(p_req1988.ownCur));//币种-人民币
        xmlWriter.writeElementString("pay_acname", p_req1988.ownActName, true);//付款户名

        xmlWriter.writeElementString("as_flag", "0");//是否使用账簿号 0：不需要 1：需要
        xmlWriter.writeElementString("as_acno", "", true);//账簿号
        xmlWriter.writeElementString("supply_item", "0");//项目编号

        xmlWriter.writeElementString("amt", p_req1988.totalAmt);//总金额
        xmlWriter.writeElementString("count", p_req1988.totalNum);//总笔数
        xmlWriter.writeElementString("purpose", p_req1988.reqBatchNO+"代发工资");//用途
        xmlWriter.writeElementString("postscript", "", true);//附言
        xmlWriter.writeElementString("file_name", fileName);//提交的文件名
        xmlWriter.writeEndElement();//</body>
        xmlWriter.writeEndDocument();

        String[] retStrArr = sendToBank(xmlWriter.toXmlString());

        if (retStrArr[0].length() == 0) {
            StringBuilder tmpSbMsg = new StringBuilder();
            XmlTextReader tmpBkReader = loadBankRespXmlReader(retStrArr[1], tmpSbMsg);
            if (tmpBkReader != null) {
                String tmpRetCode = tmpBkReader.getFirstText("/ap/head/ret_code");
                String tmpRetInfo = tmpBkReader.getFirstText("/ap/head/ret_info");
                String tmpRetRxtInfo = tmpBkReader.getFirstText("/ap/head/ext_info");
                String tmpSuccFlag = tmpBkReader.getFirstText("/ap/head/succ_flag");
                if ("0000".equals(tmpRetCode)) {
                    if ("0".equals(tmpSuccFlag)) {
                        retAts.respCode = "0";
                        retAts.respInfo = tmpRetInfo;
//                        retAts.newReqSeqID = p_req1988.reqHeader.reqSeqID;
                        retAts.transState = "5";
                        retAts.payInfoCode = retAts.transState;
                        retAts.writeRetToATS();
                    } else if ("1".equals(tmpSuccFlag)) {
                        retAts.writeRespCode("-1");
                        retAts.writeRespInfo("前置返回错误，网络问题、需要查证处理");
                        retAts.transState = "8";
                        retAts.payInfoCode = retAts.transState;
                    } else if ("8".equals(tmpSuccFlag)) {
                        retAts.writeRespCode("-1");
                        retAts.writeRespInfo("结果未知，需要查证处理");
                        retAts.transState = "8";
                        retAts.payInfoCode = retAts.transState;
                    } else {
                        retAts.writeRespCode("-1");
                        retAts.writeRespInfo("失败");
                        retAts.transState = "6";
                        retAts.payInfoCode = retAts.transState;
                    }
                } else {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpRetInfo);
                    retAts.writeRetToATS();
                }
            } else {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(tmpSbMsg.toString());
                retAts.writeRetToATS();
            }
        } else {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(retStrArr[1]);
            retAts.writeRetToATS();
        }

        return retAts;
    }

    @Override
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req1998.reqHeader);
        retAts.reqSeqID = p_req1998.reqBatchNO;
        RetAtsBatPayRecDetail detail = new RetAtsBatPayRecDetail();
        HSBANK01Header bankHeader = new HSBANK01Header();
        bankHeader.trCode = "200201";
        bankHeader.reqNo = p_req1998.reqHeader.transSeqID;
        XmlTextWriter xmlWriter = new XmlTextWriter();
        writeCommonHeader(xmlWriter, bankHeader);
        xmlWriter.writeStartElement("body");
        xmlWriter.writeElementString("batch_no", p_req1998.reqBatchNO);
        xmlWriter.writeElementString("serial_no", "", true);
//        xmlWriter.writeElementString("serial_no", serialNo);
        xmlWriter.writeElementString("cms_corp_no", bankFront.corpNo);
        Date d = new Date();
        xmlWriter.writeElementString("tr_acdt", Format.Date8Format.format(d));
        xmlWriter.writeEndElement();//body
        xmlWriter.writeEndElement();//ap
        xmlWriter.writeEndDocument();

        String[] retStrArr = sendToBank(xmlWriter.toXmlString());

//        String f = "<?xml version=\"1.0\" encoding=\"utf-16\"?>\n" +
//                "<ap>\n" +
//                "  <head>\n" +
//                "    <tr_code>200201</tr_code>\n" +
//                "    <cms_corp_no>203480539</cms_corp_no>\n" +
//                "    <user_no>\n" +
//                "    </user_no>\n" +
//                "    <req_no>1743135372</req_no>\n" +
//                "    <serial_no>\n" +
//                "    </serial_no>\n" +
//                "    <tr_acdt>20200311</tr_acdt>\n" +
//                "    <tr_time>174313</tr_time>\n" +
//                "    <succ_flag>0</succ_flag>\n" +
//                "    <ret_info>交易成功</ret_info>\n" +
//                "    <ret_code>0000</ret_code>\n" +
//                "    <ext_info>\n" +
//                "    </ext_info>\n" +
//                "    <reserved>\n" +
//                "    </reserved>\n" +
//                "    <file_flag>1</file_flag>\n" +
//                "    <org_code>\n" +
//                "    </org_code>\n" +
//                "  </head>\n" +
//                "  <body>\n" +
//                "    <record_num>3</record_num>\n" +
//                "    <field_num>12</field_num>\n" +
//                "    <file_name>20200311172810650_I1QB</file_name>\n" +
//                "  </body>\n" +
//                "</ap>";
//        String[] retStrArr = new String[]{"", f};

        if (retStrArr[0].length() == 0) {
            StringBuilder tmpSbMsg = new StringBuilder();
            XmlTextReader tmpBkReader = loadBankRespXmlReader(retStrArr[1], tmpSbMsg);

            if (tmpBkReader != null) {
                String tmpRetCode = tmpBkReader.getFirstText("/ap/head/ret_code");
                String tmpRetInfo = tmpBkReader.getFirstText("/ap/head/ret_info");
                String tmpSuccFlag = tmpBkReader.getFirstText("/ap/head/succ_flag");
                if ("0000".equals(tmpRetCode)) {
                    retAts.respCode = "0";
                    int count = Integer.parseInt(tmpBkReader.getFirstText("/ap/body/record_num"));//记录条数
                    /*                    交易序号0|收款账号(C35)1|收款账号币种(C2)2|收款账号户名(C70)3|卡标志位4|金额5|摘要6|交易日期7|交易时间8|状态9|错误信息10|批次号11|*/
                    String fileFlag = tmpBkReader.getFirstText("/ap/head/file_flag");
                    String filename = tmpBkReader.getFirstText("/ap/body/file_name");
                    if (!StringHelper.isNullOrEmpty(filename)) {
                        String p_FileFullPath = getTempFileDirectory() + File.separator + Format.Time6Format.format(new Date());//下载到的本地路径
                        String downloadFilePath = trimEndFileSp(bankFront.bkTransFolder) + File.separator;//共享目录路径
                        StringBuilder p_sb = new StringBuilder();
                        if (SmbFileUtil.smbDownloadInChar(p_FileFullPath, downloadFilePath, filename, p_sb) == 1) {//从远程共享目录下载文件（密码包含特殊字符）
                            WriteBankLogLn("共享目录文件，位于：" + downloadFilePath);
                            WriteBankLogLn("文件下载成功，位于：" + p_FileFullPath);
                            p_FileFullPath = p_FileFullPath + File.separator + filename;
                        } else {
                            retAts.writeRespCode("-1");
                            retAts.writeRespInfo(p_sb.toString());
                            retAts.writeEnd();
                            return retAts;
                        }
                        if (existFile(p_FileFullPath)) {
                            String fileContent = new String();
                            fileContent = readFileText(p_FileFullPath, getCharset());
                            WriteBankLogLn("银行查询文件返回内容为：" + fileContent);
                            int curFieldNum = Integer.parseInt(tmpBkReader.getFirstText("/ap/body/field_num"));//字段数
                            StringBuilder curSbLog = new StringBuilder();
                            ArrayList<String[]> curDataList = MFSHelper.getTextArray(fileContent, "|", curFieldNum, count + 1, curSbLog);
                            if (curSbLog.length() == 0) {
                                for (int i = 1; i < curDataList.size(); i++) {
                                    detail = new RetAtsBatPayRecDetail();
                                    String[] curRowDataArr = curDataList.get(i);
                                    // 0交易序号|1账号|2币种|3账户名|4卡折标识|5金额|6摘要|7交易日期|8交易时间|9状态|10错误信息|11批次号|
                                    detail.memo = curRowDataArr[10].trim();
                                    detail.recAct = curRowDataArr[1].trim();
                                    detail.recName = curRowDataArr[3].trim();
                                    detail.payAmount = curRowDataArr[5].trim();
                                    detail.postScript = curRowDataArr[6].trim();
                                    detail.result = curRowDataArr[9].trim();
                                    detail.payInfoCode = detail.result;
                                    retAts.writeRetDetail(detail);
                                }
                            }
                        } else {
                            retAts.writeRespCode("-1");
                            retAts.writeRespInfo(p_FileFullPath + "对应路径不存在，请检查前置机所在文件夹");
                        }
                    } else if ("0".equals(fileFlag)) {
                        String fileContent = new String();
                        fileContent = tmpBkReader.getFirstText("/ap/body/serial_record");
                        int curFieldNum = Integer.parseInt(tmpBkReader.getFirstText("/ap/body/field_num"));
                        StringBuilder curSbLog = new StringBuilder();
                        ArrayList<String[]> curDataList = MFSHelper.getTextArray(fileContent, "|", curFieldNum, count + 1, curSbLog);
                        if (curSbLog.length() == 0) {
                            for (int i = 1; i < curDataList.size(); i++) {
                                detail = new RetAtsBatPayRecDetail();
                                String[] curRowDataArr = curDataList.get(i);
                                detail.memo = curRowDataArr[10].trim();
                                detail.postScript = curRowDataArr[6].trim();
                                detail.result = curRowDataArr[9].trim();
                                detail.payInfoCode = curRowDataArr[9].trim();
                                detail.recAct = curRowDataArr[1].trim();
                                detail.recName = curRowDataArr[3].trim();
                                detail.payAmount = curRowDataArr[5].trim();
                                detail.curType = getBankConfig().getMapKeyByValue("currencyMapping", curRowDataArr[2].trim());
                                retAts.writeRetDetail(detail);
                            }
                        }
                    } else {
                        retAts.respInfo = "银行未返回file_name节点，请检查报文";
                    }
                } else {
                    retAts.writeStart();
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpRetInfo);
                }
            } else {
                retAts.writeStart();
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(tmpSbMsg.toString());
            }
        } else {
            retAts.writeStart();
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(retStrArr[1]);
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        return null;
    }

    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        return null;
    }

    public Boolean bankWriteFile(String path, String fileName, StringBuilder content) {
        Boolean retBool = false;
        if (StringHelper.isNullOrEmpty(path)) {
            WriteBankLogLn("文件夹位置为空");
            return retBool;
        }

        if (StringHelper.isNullOrEmpty(fileName)) {
            WriteBankLogLn("文件名为空");
            return retBool;
        }

        if (StringHelper.isNullOrEmpty(content.toString())) {
            WriteBankLogLn("文件内容为空");
            return retBool;
        }

        path = trimEndFileSp(path);
        String fullPath = path + "/" + fileName;
//        String fullPath = path + File.separator + fileName;
        //共享目录
        if (path.startsWith("smb://")) {
            StringBuilder tmpSbFile = new StringBuilder();
            try {
                int retUpload = SmbFileUtil.smbWrite(fullPath, content.toString(), getCharset(), tmpSbFile);
                if (retUpload < 0) {
                    WriteBankLogLn("写入共享目录出错 ：" + fullPath);
                    return false;
                } else {
                    return true;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                WriteBankLogLn("写入共享目录出错 ：" + fullPath);
                return false;
            }
        }
        //本地
        else if (!existFile(path)) {
            WriteBankLogLn("文件夹" + path + "不存在，创建对应目录");
            mkdir(path);
            WriteBankLogLn(path + "创建成功");
        }


        try {
            WriteBankLogLn("开始写入文件" + fullPath);
            writeFile(fullPath, content.toString(), getCharset());
            WriteBankLogLn("写入完成");
            retBool = true;
        } catch (Exception ex) {
            ex.printStackTrace();
            WriteBankLogLn("写入文件失败");
            retBool = false;
        }
        return retBool;
    }

}
